import { defineStore } from 'pinia'
import { getobjm } from '../utils/getobjm.js'
import { useTreeStore } from '@/stores/treeStore.js'

export const useEarthStore = defineStore('earth', () => {
  const objm = getobjm()
  const treeStore = useTreeStore()

  // 初始化 Cesium Viewer
  const initializationEarth = async (containerId) => {
    if (!containerId) return
    //创建一个 Cesium 视口,并且绑定一个div容器earth  // 注意：此时创建的只是一个空白地球，没有纹理
    const cesiumViewer = await objm.createCesiumViewer(containerId)
    cesiumViewer.ionAccessToken =
      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJhNGNhZTA5NC1mNjA1LTRhM2UtYmYxMi1hY2IyY2RjOTE4ZTEiLCJpZCI6MzA4NjE5LCJpYXQiOjE3NDg5MTUzMzd9.7icQyNIlJ826o81yrYhIG8RTDmNgC3TYRvR4XhNjhlA'
    //尝试获取 public /scene.json
    //初始化场景
    try {
      fetch('./scene.json').then(async (res) => {
        if (res.ok) {
          res
            .json()
            .then(async (json) => {
              //加载默认
              objm.json = json
              //加载图层
              const sceneObjectESImageryLayer = objm.createSceneObjectFromJson({
                id: '90ec1f9c-9597-4b2f-9399-7af8162918dd',
                type: 'ESImageryLayer',
                name: '全球影像',
                url: 'https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
                maximumLevel: 18,
              })
              const jsonESImageryLayer = sceneObjectESImageryLayer.json
              await objm.destroySceneObject(sceneObjectESImageryLayer)
              setTimeout(() => {
                const addTree = treeStore.createSceneObjectTreeItemFromJson(jsonESImageryLayer)
                if (addTree) treeStore.treeChange()
              })
              ElMessage({
                showClose: true,
                grouping: true,
                message: '加载默认场景成功',
                type: 'success',
                duration: 1500,
              })
            })
            .catch((error) => {
              console.log(error)
              ElMessage.error('加载默认场景失败')
            })
        } else {
          ElMessage.error('加载默认场景失败')
        }
      })
    } catch (error) {
      console.log(error)
    }


    
    //每当有新视口创建的时候便会触发这个事件
    objm.viewerCreatedEvent.don(async () => {
      //添加地形  原生Cesium方式
      cesiumViewer.viewer.terrainProvider = await Cesium.CesiumTerrainProvider.fromIonAssetId(1)
      //默认飞入点  (重庆 来福士)
      objm.activeViewer.flyIn(
        [106.62672254553621, 29.572460283514193, 3073.8116032563867],
        [258.5919406761868, -27.42679133546573, 0.00013239674423600495],
        3,
      )
    })
  }

  return { initializationEarth }
})
